<template>
  <div class="goods-image">
    <!-- 大图容器 -->
    <div
      class="large"
      v-if="isShow"
      :style="{
        backgroundImage: `url(${images[currIndex]})`,
        backgroundPositionX: -2 * left + 'px',
        backgroundPositionY: -2 * top + 'px'
      }"
    ></div>
    <div
      class="middle"
      ref="target"
      @mouseenter="isShow = true"
      @mouseleave="isShow = false"
    >
      <img :src="images[currIndex]" alt="" />
      <div
        v-if="isShow"
        class="layer"
        :style="{ left: left + 'px', top: top + 'px' }"
      ></div>
    </div>
    <ul class="small">
      <li
        v-for="(img, i) in images"
        :key="img"
        :class="{ active: i === currIndex }"
      >
        <img @mouseenter="currIndex = i" :src="img" alt="" />
      </li>
    </ul>
  </div>
</template>
<script>
import { reactive, ref, watch } from 'vue'
import { toRefs, useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    images: {
      type: Array,
      default: () => []
    }
  },
  setup (props) {
    const currIndex = ref(0)
    // dom元素
    const target = ref(null)
    // 鼠标坐标信息转响应式
    const positionInfo = reactive({
      left: 0,
      top: 0,
      isShow: false
    })
    // 获取鼠标坐标
    const { elementX, elementY, isOutside } = useMouseInElement(target)

    // 侦听鼠标坐标信息做相关操作
    watch([elementX, elementY, isOutside], () => {
      if (!isOutside.value) {
        let x = elementX.value - 100
        let y = elementY.value - 100
        x = x < 0 ? 0 : x
        x = x > 200 ? 200 : x
        y = y < 0 ? 0 : y
        y = y > 200 ? 200 : y
        positionInfo.left = x
        positionInfo.top = y
      }
    })

    return { target, currIndex, ...toRefs(positionInfo) }
  }
}
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
